﻿using Consul;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.Web.Core.Register
{
    public class ConsulRegister: IConsulRegister
    {
        private readonly ConsulRegisterOptions _consulRegisterOptions;

        public ConsulRegister(IOptionsMonitor<ConsulRegisterOptions> consulRegisterOptions)
        {
            _consulRegisterOptions = consulRegisterOptions.CurrentValue;
        }

        public async Task ConsulRegistAsync()
        {
            var client = new ConsulClient(options => { 
               options.Address=new Uri(_consulRegisterOptions.Address);
            });

            var registration = new AgentServiceRegistration {
                ID = Guid.NewGuid().ToString(),
                Name = _consulRegisterOptions.Name,
                Address = _consulRegisterOptions.Ip,
                Port = Convert.ToInt32(_consulRegisterOptions.Port),
                Check = new AgentServiceCheck {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                    Interval=TimeSpan.FromSeconds(10),
                    HTTP=$"http://{_consulRegisterOptions.Ip}:{_consulRegisterOptions.Port}{_consulRegisterOptions.HealthCheck}",
                    Timeout=TimeSpan.FromSeconds(5)
                }
            };

            await client.Agent.ServiceRegister(registration);
        }
    }
}
